package com.getpebble.android.framework.endpoint;

import android.content.ContentResolver;
import android.os.Handler;
import android.os.Looper;
import com.getpebble.android.bluetooth.protocol.ProtocolMessage;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.framework.install.PebbleManifest.ResourceInfo;
import com.getpebble.android.common.framework.install.PutBytesType;
import com.getpebble.android.common.model.PblDeviceModel;
import com.getpebble.android.common.model.PblDeviceModel.PblDeviceRecord;
import com.getpebble.android.framework.comm.MessageRouter;
import com.getpebble.android.framework.endpoint.PutBytesEndpoint.InstallResult;
import com.getpebble.android.framework.install.firmware.FirmwareBundle;
import com.getpebble.android.framework.protocol.EndpointId;
import com.getpebble.android.framework.protocol.inbound.FirmwareUpdateResponseType;
import com.getpebble.android.framework.protocol.inbound.PblInboundSystemMessage;
import com.getpebble.android.framework.protocol.inbound.PblInboundSystemMessage.Type;
import com.getpebble.android.framework.protocol.outbound.PblOutboundSystemMessage.SysMsgCommand;
import com.getpebble.android.framework.util.PebbleCapabilities;
import com.google.common.primitives.UnsignedInteger;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;
import java.io.IOException;
import java.io.InputStream;

public class InstallFirmwareEndpointSet extends EndpointSet {
    private static final String TAG = InstallFirmwareEndpointSet.class.getSimpleName();
    private ContentResolver mContentResolver;
    private FirmwareBundle mFirmwareBundle;
    private Handler mHandler;
    private Listener mListener;
    private final PutBytesEndpoint mPutBytesEndpoint;
    private final Listener mPutBytesEndpointListener = new Listener() {
        public void progressUpdated(UnsignedInteger current, UnsignedInteger max) {
            int percentage;
            switch (AnonymousClass4.$SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallState[InstallFirmwareEndpointSet.this.mState.ordinal()]) {
                case SMTPMessage.RETURN_FULL /*1*/:
                    percentage = current.times(UnsignedInteger.fromIntBits(100)).dividedBy(max).intValue();
                    if (InstallFirmwareEndpointSet.this.mFirmwareBundle.hasResources()) {
                        percentage = (percentage / 2) + 50;
                        break;
                    }
                    break;
                case SMTPMessage.RETURN_HDRS /*2*/:
                    percentage = current.times(UnsignedInteger.fromIntBits(100)).dividedBy(max).intValue() / 2;
                    break;
                default:
                    Trace.warning(InstallFirmwareEndpointSet.TAG, "Got progress updated callback while in state: " + InstallFirmwareEndpointSet.this.mState + "; dropping");
                    return;
            }
            Listener listener = InstallFirmwareEndpointSet.this.getListener();
            if (listener != null) {
                listener.installProgressUpdate(percentage);
            }
        }

        public void transferComplete(UnsignedInteger cookie) {
            switch (AnonymousClass4.$SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallState[InstallFirmwareEndpointSet.this.mState.ordinal()]) {
                case SMTPMessage.RETURN_FULL /*1*/:
                    InstallFirmwareEndpointSet.this.mState = FirmwareInstallState.INSTALLING_FIRMWARE;
                    if (cookie == null) {
                        InstallFirmwareEndpointSet.this.mState = FirmwareInstallState.FAILED;
                        InstallFirmwareEndpointSet.this.sendResult(FirmwareInstallResult.FIRMWARE_LOAD_FAILED);
                        return;
                    }
                    InstallFirmwareEndpointSet.this.mPutBytesEndpoint.install(cookie);
                    return;
                case SMTPMessage.RETURN_HDRS /*2*/:
                    InstallFirmwareEndpointSet.this.mResourcesCookie = cookie;
                    InstallFirmwareEndpointSet.this.sendFirmware();
                    return;
                default:
                    return;
            }
        }

        public void transferFailed(InstallResult installResult) {
            FirmwareInstallResult result;
            switch (AnonymousClass4.$SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallState[InstallFirmwareEndpointSet.this.mState.ordinal()]) {
                case SMTPMessage.RETURN_FULL /*1*/:
                    result = FirmwareInstallResult.FIRMWARE_LOAD_FAILED;
                    if (installResult.equals(InstallResult.INVALID_CRC)) {
                        result = FirmwareInstallResult.INVALID_FIRMWARE_CRC;
                    }
                    InstallFirmwareEndpointSet.this.mState = FirmwareInstallState.FAILED;
                    InstallFirmwareEndpointSet.this.sendResult(result);
                    return;
                case SMTPMessage.RETURN_HDRS /*2*/:
                    result = FirmwareInstallResult.RESOURCE_LOAD_FAILED;
                    if (installResult.equals(InstallResult.INVALID_CRC)) {
                        result = FirmwareInstallResult.INVALID_RESOURCE_CRC;
                    } else if (installResult.equals(InstallResult.TIMEOUT)) {
                        result = FirmwareInstallResult.TIMEOUT;
                    }
                    InstallFirmwareEndpointSet.this.mState = FirmwareInstallState.FAILED;
                    InstallFirmwareEndpointSet.this.sendResult(result);
                    return;
                default:
                    return;
            }
        }

        public void installComplete(UnsignedInteger cookie) {
            switch (AnonymousClass4.$SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallState[InstallFirmwareEndpointSet.this.mState.ordinal()]) {
                case ListInfo.INDETERMINATE /*3*/:
                    InstallFirmwareEndpointSet.this.mState = FirmwareInstallState.INSTALLING_RESOURCES;
                    InstallFirmwareEndpointSet.this.mPutBytesEndpoint.install(InstallFirmwareEndpointSet.this.mResourcesCookie);
                    return;
                case SMTPMessage.NOTIFY_DELAY /*4*/:
                    InstallFirmwareEndpointSet.this.sendInstallComplete();
                    InstallFirmwareEndpointSet.this.mState = FirmwareInstallState.COMPLETE;
                    InstallFirmwareEndpointSet.this.sendResult(FirmwareInstallResult.OK);
                    return;
                default:
                    return;
            }
        }

        public void installFailed(InstallResult installResult) {
            InstallFirmwareEndpointSet.this.mState = FirmwareInstallState.FAILED;
            InstallFirmwareEndpointSet.this.sendInstallFailed();
            switch (AnonymousClass4.$SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallState[InstallFirmwareEndpointSet.this.mState.ordinal()]) {
                case ListInfo.INDETERMINATE /*3*/:
                    InstallFirmwareEndpointSet.this.sendResult(FirmwareInstallResult.FIRMWARE_LOAD_FAILED);
                    return;
                case SMTPMessage.NOTIFY_DELAY /*4*/:
                    InstallFirmwareEndpointSet.this.sendResult(FirmwareInstallResult.RESOURCE_LOAD_FAILED);
                    return;
                default:
                    return;
            }
        }
    };
    private UnsignedInteger mResourcesCookie;
    private Runnable mResponseTimeoutRunnable = new Runnable() {
        public void run() {
            synchronized (InstallFirmwareEndpointSet.this) {
                InstallFirmwareEndpointSet.this.mState = FirmwareInstallState.FAILED;
                InstallFirmwareEndpointSet.this.sendResult(FirmwareInstallResult.TIMEOUT);
            }
        }
    };
    private FirmwareInstallState mState = FirmwareInstallState.NOT_STARTED;
    private SystemMessageEndpoint mSystemMessageEndpoint;

    static /* synthetic */ class AnonymousClass4 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallState = new int[FirmwareInstallState.values().length];
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$protocol$EndpointId = new int[EndpointId.values().length];
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundSystemMessage$Type = new int[Type.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$EndpointId[EndpointId.SYSTEM_MESSAGE.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$EndpointId[EndpointId.PUT_BYTES.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallState[FirmwareInstallState.SENDING_FIRMWARE.ordinal()] = 1;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallState[FirmwareInstallState.SENDING_RESOURCES.ordinal()] = 2;
            } catch (NoSuchFieldError e4) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallState[FirmwareInstallState.INSTALLING_FIRMWARE.ordinal()] = 3;
            } catch (NoSuchFieldError e5) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallFirmwareEndpointSet$FirmwareInstallState[FirmwareInstallState.INSTALLING_RESOURCES.ordinal()] = 4;
            } catch (NoSuchFieldError e6) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundSystemMessage$Type[Type.FIRMWARE_UPDATE_START_ACK.ordinal()] = 1;
            } catch (NoSuchFieldError e7) {
            }
        }
    }

    public enum FirmwareInstallResult {
        OK(0),
        CANCELLED(-1),
        WRONG_HW_VERSION(-2),
        BUNDLE_NOT_FOUND(-3),
        FIRMWARE_START_FAILED(-4),
        RESOURCE_LOAD_FAILED(-5),
        FIRMWARE_LOAD_FAILED(-6),
        INVALID_RESOURCE_CRC(-7),
        INVALID_FIRMWARE_CRC(-8),
        TIMEOUT(-9),
        UNKNOWN_ERROR(-10),
        ENDPOINT_NOT_ACTIVE(-11),
        INVALID(-12),
        NO_DEVICE_CONNECTED(-13);
        
        private int mCode;

        private FirmwareInstallResult(int code) {
            this.mCode = code;
        }

        public int getCode() {
            return this.mCode;
        }

        public static FirmwareInstallResult fromCode(int code) {
            for (FirmwareInstallResult result : values()) {
                if (result.getCode() == code) {
                    return result;
                }
            }
            return UNKNOWN_ERROR;
        }
    }

    private enum FirmwareInstallState {
        NOT_STARTED,
        WAITING_FOR_SYSTEM_MESSAGE,
        SENDING_RESOURCES,
        SENDING_FIRMWARE,
        INSTALLING_RESOURCES,
        INSTALLING_FIRMWARE,
        COMPLETE,
        FAILED
    }

    public interface Listener {
        void installFail(FirmwareInstallResult firmwareInstallResult);

        void installProgressUpdate(int i);

        void installSuccess(FirmwareInstallResult firmwareInstallResult);
    }

    public InstallFirmwareEndpointSet(MessageRouter router, FirmwareBundle firmwareBundle, Listener listener, ContentResolver resolver) {
        super(router);
        if (firmwareBundle == null) {
            throw new IllegalArgumentException("'FirmwareBundle' must not be null!");
        } else if (resolver == null) {
            throw new IllegalArgumentException("'resolver' must not be null!");
        } else {
            this.mFirmwareBundle = firmwareBundle;
            this.mListener = listener;
            this.mHandler = new Handler(Looper.getMainLooper());
            this.mContentResolver = resolver;
            this.mPutBytesEndpoint = new PutBytesEndpoint(this);
            this.mPutBytesEndpoint.lock(this.mPutBytesEndpointListener);
        }
    }

    protected void onInit() {
    }

    private Listener getListener() {
        return this.mListener;
    }

    private IEndpointMessageSender getMessageSender() {
        return this;
    }

    private SystemMessageEndpoint getSystemMessageEndpoint() {
        if (this.mSystemMessageEndpoint == null) {
            this.mSystemMessageEndpoint = new SystemMessageEndpoint(getMessageSender());
        }
        return this.mSystemMessageEndpoint;
    }

    private void startTimeout() {
        this.mHandler.postDelayed(this.mResponseTimeoutRunnable, 5000);
    }

    private void cancelTimeout() {
        this.mHandler.removeCallbacks(this.mResponseTimeoutRunnable);
    }

    private void sendResult(FirmwareInstallResult result) {
        cancelTimeout();
        Listener listener = getListener();
        if (listener == null) {
            Trace.error(TAG, "Listener is null!");
            return;
        }
        if (result.equals(FirmwareInstallResult.OK)) {
            listener.installSuccess(result);
        } else {
            listener.installFail(result);
        }
        if (this.mFirmwareBundle != null) {
            this.mFirmwareBundle.closeFile();
        }
    }

    public synchronized void startInstall() {
        if (isActive()) {
            FirmwareInstallResult result = doPreCheck();
            if (result != FirmwareInstallResult.OK) {
                this.mState = FirmwareInstallState.FAILED;
                sendResult(result);
            } else if (deviceSupportsFirmwareUpdateAck()) {
                sendFirmwareStartMessage();
            } else if (this.mFirmwareBundle.hasResources()) {
                sendResources();
            } else {
                sendFirmware();
            }
        } else {
            this.mState = FirmwareInstallState.FAILED;
            sendResult(FirmwareInstallResult.ENDPOINT_NOT_ACTIVE);
        }
    }

    private synchronized void sendFirmwareStartMessage() {
        this.mState = FirmwareInstallState.WAITING_FOR_SYSTEM_MESSAGE;
        getSystemMessageEndpoint().setListener(new com.getpebble.android.framework.endpoint.SystemMessageEndpoint.Listener() {
            public void onSystemMessage(PblInboundSystemMessage message) {
                switch (AnonymousClass4.$SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundSystemMessage$Type[message.getType().ordinal()]) {
                    case SMTPMessage.RETURN_FULL /*1*/:
                        try {
                            FirmwareUpdateResponseType response = FirmwareUpdateResponseType.from(message);
                            InstallFirmwareEndpointSet.this.cancelTimeout();
                            if (!response.equals(FirmwareUpdateResponseType.FIRMWARE_UPDATE_RUNNING)) {
                                InstallFirmwareEndpointSet.this.mState = FirmwareInstallState.FAILED;
                                InstallFirmwareEndpointSet.this.sendResult(FirmwareInstallResult.FIRMWARE_START_FAILED);
                                return;
                            } else if (InstallFirmwareEndpointSet.this.mFirmwareBundle.hasResources()) {
                                InstallFirmwareEndpointSet.this.sendResources();
                                return;
                            } else {
                                InstallFirmwareEndpointSet.this.sendFirmware();
                                return;
                            }
                        } catch (IllegalArgumentException e) {
                            Trace.warning(InstallFirmwareEndpointSet.TAG, "Invalid firmware update response", e);
                            return;
                        }
                    default:
                        Trace.info(InstallFirmwareEndpointSet.TAG, "Dropping system message of type: " + message.getType().toString());
                        return;
                }
            }
        });
        getSystemMessageEndpoint().sendSystemMessage(SysMsgCommand.FIRMWARE_START);
        startTimeout();
    }

    private synchronized void sendResources() {
        this.mState = FirmwareInstallState.SENDING_RESOURCES;
        String name = this.mFirmwareBundle.getManifest().getResourceInfo().getName();
        try {
            InputStream inputStream = this.mFirmwareBundle.getInputStreamForComponent(name);
            int size = this.mFirmwareBundle.getManifest().getResourceInfo().getSize();
            this.mPutBytesEndpoint.setInstallType(PutBytesType.SYS_RESOURCES).setInputStream(inputStream).setName(name).setSize(size).setExpectedCrc(this.mFirmwareBundle.getManifest().getResourceInfo().getCrc()).setAppBank(0);
            this.mPutBytesEndpoint.startTransfer();
        } catch (IOException e) {
            Trace.error(TAG, "Failed to set up put bytes endpoint when transferring resources", e);
            this.mState = FirmwareInstallState.FAILED;
            sendResult(FirmwareInstallResult.RESOURCE_LOAD_FAILED);
        }
    }

    private synchronized void sendFirmware() {
        this.mState = FirmwareInstallState.SENDING_FIRMWARE;
        String name = this.mFirmwareBundle.getManifest().getFirmware().getName();
        try {
            InputStream inputStream = this.mFirmwareBundle.getInputStreamForComponent(name);
            int size = this.mFirmwareBundle.getManifest().getFirmware().getSize();
            this.mPutBytesEndpoint.setInstallType(PutBytesType.FIRMWARE).setInputStream(inputStream).setName(name).setSize(size).setExpectedCrc(this.mFirmwareBundle.getManifest().getFirmware().getCrc()).setAppBank(this.mFirmwareBundle.hasResources() ? 2 : 1);
            this.mPutBytesEndpoint.startTransfer();
        } catch (IOException ioe) {
            Trace.error(TAG, "Failed to get firmware from bundle.", ioe);
            this.mState = FirmwareInstallState.FAILED;
            sendResult(FirmwareInstallResult.FIRMWARE_LOAD_FAILED);
        }
    }

    private void sendInstallComplete() {
        Trace.debug(TAG, "sendInstallComplete()");
        getSystemMessageEndpoint().sendSystemMessage(SysMsgCommand.FIRMWARE_COMPLETE);
    }

    private void sendInstallFailed() {
        Trace.debug(TAG, "sendInstallFailed()");
        getSystemMessageEndpoint().sendSystemMessage(SysMsgCommand.FIRMWARE_FAIL);
    }

    private FirmwareInstallResult doPreCheck() {
        if (!isFirmwareBundleValid()) {
            return FirmwareInstallResult.UNKNOWN_ERROR;
        }
        if (!isFirmwareCompatible()) {
            return FirmwareInstallResult.WRONG_HW_VERSION;
        }
        if (isRecoveryAndCanHandle()) {
            return FirmwareInstallResult.OK;
        }
        return FirmwareInstallResult.UNKNOWN_ERROR;
    }

    private boolean isFirmwareBundleValid() {
        if (this.mFirmwareBundle.getManifest().getFirmware() == null || !isResourceInfoValid(this.mFirmwareBundle.getManifest().getFirmware()) || this.mFirmwareBundle.getManifest().getFirmware().getHardwareRevision() == null) {
            return false;
        }
        if (!this.mFirmwareBundle.hasResources() || isResourceInfoValid(this.mFirmwareBundle.getManifest().getResourceInfo())) {
            return true;
        }
        return false;
    }

    private boolean isResourceInfoValid(ResourceInfo resourceInfo) {
        if (resourceInfo.getCrc() == null || resourceInfo.getSize() <= 0 || resourceInfo.getName() == null) {
            return false;
        }
        return true;
    }

    private boolean deviceSupportsFirmwareUpdateAck() {
        PblDeviceRecord deviceRecord = PblDeviceModel.getPblDeviceRecord(this.mContentResolver, getDevice());
        if (deviceRecord == null || deviceRecord.fwVersion == null || !PebbleCapabilities.remoteSendsFirmwareUpdateAck(deviceRecord.fwVersion)) {
            return false;
        }
        return true;
    }

    private boolean isFirmwareCompatible() {
        if (this.mFirmwareBundle == null) {
            Trace.warning(TAG, "isFirmwareCompatible: null mFirmwareBundle");
            return false;
        }
        PblDeviceRecord deviceRecord = PblDeviceModel.getPblDeviceRecord(this.mContentResolver, getDevice());
        if (deviceRecord == null) {
            return false;
        }
        try {
            if (this.mFirmwareBundle.getManifest().getFirmware().getHardwareRevision().equals(deviceRecord.hwPlatform)) {
                return true;
            }
            return false;
        } catch (NullPointerException e) {
            Trace.warning(TAG, "isFirmwareCompatible NPE", e);
            return false;
        }
    }

    private boolean isRecoveryAndCanHandle() {
        return true;
    }

    public synchronized boolean handleMessage(ProtocolMessage protocolMessage) {
        boolean onReceive;
        EndpointId endpointId = EndpointId.fromCode(protocolMessage.getEndpointId());
        switch (AnonymousClass4.$SwitchMap$com$getpebble$android$framework$protocol$EndpointId[endpointId.ordinal()]) {
            case SMTPMessage.RETURN_FULL /*1*/:
                onReceive = getSystemMessageEndpoint().onReceive(protocolMessage);
                break;
            case SMTPMessage.RETURN_HDRS /*2*/:
                onReceive = this.mPutBytesEndpoint.onReceive(protocolMessage);
                break;
            default:
                Trace.verbose(TAG, "Ignoring message for endpoint: " + endpointId);
                onReceive = false;
                break;
        }
        return onReceive;
    }

    public void onMessageSendSuccess() {
        Trace.verbose(TAG, "Message send succeeded.");
    }

    public void onMessageSendFailed() {
        Trace.error(TAG, "Message send failed.");
        sendResult(FirmwareInstallResult.UNKNOWN_ERROR);
    }

    protected synchronized void onDestroy() {
        if (!(this.mState == FirmwareInstallState.COMPLETE || this.mState == FirmwareInstallState.FAILED || this.mState == FirmwareInstallState.NOT_STARTED)) {
            Trace.debug(TAG, "onDestroy: interrupted (at state " + this.mState + ")");
            this.mState = FirmwareInstallState.FAILED;
            sendResult(FirmwareInstallResult.CANCELLED);
            this.mFirmwareBundle.closeFile();
        }
    }
}
